package org.example.interceptor;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.Result;
import org.example.utils.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("Request URI: " + requestURI);
        String jwt = request.getHeader("token");
        try {
            // 验证token
            Claims claims = JWTUtils.parseToken(jwt);
            log.info("用户{}{}已登录", claims.get("name"), claims.get("id"));
            return true;
        } catch (Exception e) {
            // 验证失败
            Result error =  Result.error("NOT_LOGIN");
            String notLogin = JSON.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
    }
}
